package cn.tedu.csmall.stock.webapi.controller;

import cn.tedu.csmall.commons.exception.CoolSharkServiceException;
import cn.tedu.csmall.commons.pojo.stock.dto.StockReduceCountDTO;
import cn.tedu.csmall.commons.restful.JsonResult;
import cn.tedu.csmall.commons.restful.ResponseCode;
import cn.tedu.csmall.stock.service.service.IStockService;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
@RequestMapping("/base/stock")
@Api(tags = "库存管理模块")
public class StockController {
    @Autowired
    private IStockService service;
    @PostMapping("/reduce/count")
    @SentinelResource(value = "减少库存",blockHandler = "blockError",fallback = "fallbackError")
    @ApiOperation("减少库存")
    public JsonResult  reduceCommodityCount(StockReduceCountDTO stockReduceCountDTO){
        service.reduceCommodityCount(stockReduceCountDTO);
        if (Math.random()<0.5){

            throw new CoolSharkServiceException(ResponseCode.INTERNAL_SERVER_ERROR,"发生随机异常");
        }
//        try {
//            Thread.sleep(5000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        return JsonResult.ok("减少库存完成");
    }
    public JsonResult blockError(StockReduceCountDTO stockReduceCountDTO, BlockException e){
        return JsonResult.failed(ResponseCode.INTERNAL_SERVER_ERROR,"服务器忙");
    }
    //自定义降级方法
    public JsonResult fallbackError(StockReduceCountDTO stockReduceCountDTO, Throwable e){
        e.printStackTrace();
        return JsonResult.failed(ResponseCode.INTERNAL_SERVER_ERROR,"服务降级");
    }
}
